package com.qiuling.iot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.google.common.collect.Lists;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.List;

/**
 * @Author：zhangqiang
 * @Description：连接池配置
 * @Date：Created in 19:32 2020/2/7
 * @Modified By：
 */
@Configuration
public class DruidConfig {

    /**
     * 主要实现web监控的配置处理
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
                //表示进行druid监控的配置处理操作
                new StatViewServlet(), "/druid/*");
        //白名单(不拦截)
        servletRegistrationBean.addInitParameter("allow", allowList().toString());
        //黑名单（拦截）
        servletRegistrationBean.addInitParameter("deny", denyList().toString());
        //用户名
        servletRegistrationBean.addInitParameter("loginUsername", "root");
        //密码
        servletRegistrationBean.addInitParameter("loginPassword", "root");
        //是否可以重置数据源
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean    //监控
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        //所有请求进行监控处理
        filterRegistrationBean.addUrlPatterns("/*");
        //排除
        filterRegistrationBean.addInitParameter("exclusions",
                "/static/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置白名单
     *
     * @return
     */
    private List<String> allowList() {
        List<String> ipList = Lists.newArrayList();
        ipList.add("127.0.0.1");
        ipList.add("192.168.0.100");
        return ipList;
    }

    /**
     * 配置黑名单
     *
     * @return
     */
    private List<String> denyList() {
        List<String> ipList = Lists.newArrayList();
        ipList.add("192.168.0.1");
        ipList.add("192.168.0.5");
        return ipList;
    }


}
